<template>
  <a-form-model
    ref="ruleForm"
    :model="form"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-model-item ref="name" label="姓名" prop="name">
      <a-input
        placeholder="请输入姓名"
        v-model="form.name"
        @blur="
          () => {
            $refs.name.onFieldBlur();
          }
        "
      />
    </a-form-model-item>
    <a-form-model-item label="性别" prop="sex">
      <a-radio-group v-model="form.sex">
        <a-radio :value="1">
          男
        </a-radio>
        <a-radio :value="2">
          女
        </a-radio>
        <a-radio :value="0">
          未知
        </a-radio>
      </a-radio-group>
    </a-form-model-item>
    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit">
        保存
      </a-button>
      <a-button style="margin-left: 10px;" @click="resetForm">
        重置
      </a-button>
    </a-form-model-item>
  </a-form-model>
</template>
<script>

import { mapActions } from 'vuex'

export default {
  data () {
    return {
      userInfo: null,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: '',
      form: {
        name: '',
        sex: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20之间', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))[0]
    this.form.name = this.userInfo.name
    this.form.sex = this.userInfo.sex
  },
  methods: {
    ...mapActions('user', ['UPDATE_USER_METHOD']),
    onSubmit () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const params = {
            id: this.userInfo.id,
            name: this.form.name,
            sex: this.form.sex
          }
          this.UPDATE_USER_METHOD(params)
        } else {
          return false
        }
      })
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>
